import {Form, Input, message, Modal, Upload} from "antd";
import {useRef, useState} from "react";
import type {RcFile, UploadFile, UploadProps} from 'antd/es/upload/interface';
import imgzip from "imgzip";
import {modifyImg} from "@/services/pageImg"

// @ts-ignore
const Modify = ({data, onClose, onOk, visible}) => {

  const [files, setFiles] = useState([])
  const [form] = Form.useForm()
  const [text, setText] = useState('')
  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  const handleOk = () => {
    if (form.getFieldsValue().imgs) {
      const compress = new imgzip({quality: 1});
      console.log(form.getFieldsValue().imgs.file.thumbUrl)
      compress.photoCompress(form.getFieldsValue().imgs.file.originFileObj, base64 => {
        modifyImg({img: form.getFieldsValue().imgs.file.thumbUrl, num: data}).then(res => {
          if (res.status === 200) {
            onOk()
            message.success(res.message).then()
          } else {
            message.error(res.message).then()
          }
        })
      })
    }else{
      modifyImg({text: text, num: data}).then(res => {
        if (res.status === 200) {
          onOk()
          message.success(res.message).then()
        } else {
          message.error(res.message).then()
        }
      })
    }

  }
  // @ts-ignore
  // @ts-ignore
  return (
    <Modal title={'图文修改'}
           maskClosable={false}
           destroyOnClose
           width={'26vw'}
           visible={visible}
           onCancel={onClose}
           onOk={handleOk}
           keyboard={false}
           mask={false}>
      <Form form={form} labelCol={{span: 6}} wrapperCol={{span: 14}} autoComplete="off">
        {data != 3 &&
        <Form.Item name="imgs" rules={[{required: true, message: '请上传图片'}]}>
          <Upload
            listType="picture-card"
            accept=".jpg, .jpeg, .png"
            onPreview={onPreview}
            onChange={({fileList}) => setFiles(fileList)}
          >
            {files.length < 1 && '+ Upload'}
          </Upload>
        </Form.Item>}
        {data === 3 &&
        <Form.Item name="text" rules={[{required: true, message: '请修改'}]}>
          <Input onChange={(e) => {
            setText(e.target.value)
          }}/>
        </Form.Item>}

      </Form>
    </Modal>
  );
};

export default Modify;
